<?php 

class SSOAuthenticationFilter
{
	public function run()
	{
		$isAuthenticated = Session::instance()->get(Kohana::config('sso_auth.session_authentication_state_holder'), false);
		$isSSOModuleEnabled = Kohana::config('sso_auth.enabled');
				
		if ($isAuthenticated == false && $isSSOModuleEnabled)
		{				
			$input = Input::instance();			
			$cookie = $input->cookie(Kohana::config('sso_auth.cookie_name'));		
			$soapClient = new SoapClient(Kohana::config('sso_auth.verification_webservice_url'));
			try
			{
				$userProfile = (array)$soapClient->verifyAuthenticationToken($cookie, $input->server('HTTP_USER_AGENT'));				
								
				$eventData = array('profile' => $userProfile);
				Event::run('logintrade_sso.user_authenticated',$eventData);				
			}
			catch (\LogicException $e)
			{
				if ($e->getMessage() == 'token_not_found')
				{
					header('HTTP/1.1 403 Forbidden');
					exit;				
				}
			}					
		}
	}
}

$filter = new SSOAuthenticationFilter();

Event::add('system.pre_controller', array($filter, 'run'));